# 创建角色管理视图组件
<template>
  <div class="space-y-6">
    <!-- 搜索和添加区域 -->
    <div class="flex justify-between">
      <div class="flex gap-4">
        <a-input-search
          v-model="searchParams.keyword"
          placeholder="请输入角色名称/编码搜索"
          style="width: 320px"
          @search="handleSearch"
          allow-clear
        />
      </div>
      <a-button type="primary" @click="openAddModal">
        <template #icon><icon-plus /></template>
        添加角色
      </a-button>
    </div>

    <!-- 角色列表表格 -->
    <a-table
      :data="tableData"
      :loading="loading"
      :pagination="{
        total: pagination.total,
        current: pagination.current,
        pageSize: pagination.pageSize,
        showTotal: true,
        showJumper: true,
        showPageSize: true
      }"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      stripe
    >
      <template #columns>
        <a-table-column title="角色名称" data-index="name" />
        <a-table-column title="角色编码" data-index="code" />
        <a-table-column title="描述" data-index="description" />
        <a-table-column title="状态" data-index="status">
          <template #cell="{ record }">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="创建时间" data-index="createdAt" />
        <a-table-column title="更新时间" data-index="updatedAt" />
        <a-table-column title="操作" :width="180">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" size="small" @click="editRole(record)">
                <template #icon><icon-edit /></template>
                编辑
              </a-button>
              <a-popconfirm
                content="确定要删除该角色吗？"
                @ok="deleteRole(record)"
              >
                <a-button type="text" status="danger" size="small">
                  <template #icon><icon-delete /></template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 添加/编辑角色弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-align="right"
        :style="{ width: '600px' }"
      >
        <a-form-item field="name" label="角色名称" :rules="[{required: true, message: '请输入角色名称'}]">
          <a-input v-model="formData.name" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item field="code" label="角色编码" :rules="[{required: true, message: '请输入角色编码'}]">
          <a-input v-model="formData.code" placeholder="请输入角色编码" />
        </a-form-item>
        <a-form-item field="description" label="描述">
          <a-textarea v-model="formData.description" placeholder="请输入角色描述" />
        </a-form-item>
        <a-form-item field="status" label="状态" v-if="formData.roleId">
          <a-radio-group v-model="formData.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus, IconEdit, IconDelete } from '@arco-design/web-vue/es/icon'
import type { FieldRule } from '@arco-design/web-vue'
import { roleApi } from '@/api/role'
import type { RoleInfo, RoleCreateParams, RoleUpdateParams } from '@/types/api'

// 搜索参数
const searchParams = reactive({
  page: 1,
  size: 10,
  keyword: ''
})

// 表格相关
const loading = ref(false)
const tableData = ref<RoleInfo[]>([])
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入角色名称' }],
  code: [{ required: true, message: '请输入角色编码' }]
} as Record<string, FieldRule[]>

// 模态框相关
const modalVisible = ref(false)
const modalTitle = ref('添加角色')
const formRef = ref<any>()
const formData = reactive({
  roleId: 0,
  name: '',
  code: '',
  description: '',
  status: 1
})

// 获取角色列表
const fetchRoleList = async () => {
  try {
    loading.value = true
    const res = await roleApi.getRoleList({
      page: pagination.current,
      size: pagination.pageSize,
      keyword: searchParams.keyword
    })
    if (res.code === 1) {
      tableData.value = res.data.records
      pagination.total = res.data.total
    } else {
      Message.error(res.msg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    Message.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchRoleList()
}

// 分页变化
const onPageChange = (page: number) => {
  pagination.current = page
  fetchRoleList()
}

const onPageSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchRoleList()
}

// 打开添加弹窗
const openAddModal = () => {
  modalTitle.value = '添加角色'
  formData.roleId = 0
  formData.name = ''
  formData.code = ''
  formData.description = ''
  formData.status = 1
  modalVisible.value = true
}

// 编辑角色
const editRole = (record: RoleInfo) => {
  modalTitle.value = '编辑角色'
  Object.assign(formData, record)
  modalVisible.value = true
}

// 删除角色
const deleteRole = async (record: RoleInfo) => {
  try {
    const res = await roleApi.deleteRole(record.roleId)
    if (res.code === 1) {
      Message.success('删除成功')
      fetchRoleList()
    } else {
      Message.error(res.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    Message.error('删除失败')
  }
}

// 处理弹窗确认
const handleModalOk = async () => {
  try {
    await formRef.value?.validate()
    
    if (formData.roleId) {
      // 更新角色
      const res = await roleApi.updateRole(formData as RoleUpdateParams)
      if (res.code === 1) {
        Message.success('更新成功')
        modalVisible.value = false
        fetchRoleList()
      } else {
        Message.error(res.msg || '更新失败')
      }
    } else {
      // 创建角色
      const res = await roleApi.createRole({
        name: formData.name,
        code: formData.code,
        description: formData.description
      })
      if (res.code === 1) {
        Message.success('创建成功')
        modalVisible.value = false
        fetchRoleList()
      } else {
        Message.error(res.msg || '创建失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理弹窗取消
const handleModalCancel = () => {
  formRef.value?.resetFields()
  modalVisible.value = false
}

// 页面加载时获取角色列表
onMounted(() => {
  fetchRoleList()
})
</script> 